package com.xcity.game.common;

import java.util.concurrent.atomic.AtomicInteger;

import com.xcity.db.entity.Player;
import com.xcity.pomelo.push.msg.ConfirmBoxPush;

import naga.x.game.time.TimeUpdater;

public abstract class AbstractConfirmOperation implements ConfirmOperation {

	protected int id;
	protected long createTime;
	protected int timeout;
	protected String msg;
	protected Player ref;
	
	static final AtomicInteger ID_GEN = new AtomicInteger();
	
	public AbstractConfirmOperation(Player ref, String msg) {
		this(ref, DEFAULT_TIME_OUT, msg);
	}
	
	public AbstractConfirmOperation(Player ref, int timeoutMillis, String msg) {
		this.id = ID_GEN.incrementAndGet();
		this.createTime = TimeUpdater.getInstance().now();
		this.timeout = timeoutMillis;
		this.msg = msg;
		this.ref = ref;
	}
	
	@Override
	public void operate(byte op) {
		ref.setConfirmOperation(null);
		if (op == OK) {
			ok(ref);
		} else {
			cancel(ref);
		}
	}

	@Override
	public boolean isTimeout() {
		return TimeUpdater.getInstance().now() > createTime + timeout;
	}
	
	@Override
	public int getId() {
		return id;
	}

	@Override
	public void send() {
		ref.setConfirmOperation(this);
		ref.send(new ConfirmBoxPush(this.id, msg)); // push
		msg = null;
	}
	
	/**
	 * 确认操作
	 */
	public abstract void ok(Player player);
	
	/**
	 * 取消操作
	 */
	public void cancel(Player player) {
		// DEFAULT EMPTY
	}
	
}
